package com.example.reader.sdk.receiver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbDeviceConnection;
import android.hardware.usb.UsbManager;
import android.util.Log;

import com.example.mt3yreader.mt3yApi;
import com.example.reader.sdk.DeviceReaderA;
import com.example.reader.sdk.IReaderCallback;
import com.example.reader.sdk.bean.ReaderBean;

public class ReaderReicever extends BroadcastReceiver {
    private IReaderCallback readerCallback;
    private ReaderBean mReaderBean;
    private UsbManager mUsbManager;
    private static final String TAG = "ReaderReicever";

    public ReaderReicever(IReaderCallback readerCallback, UsbManager usbManager, ReaderBean readerBean) {
        this.readerCallback = readerCallback;
        mReaderBean = readerBean;
        mUsbManager = usbManager;
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        if (DeviceReaderA.ACTION_USB_PERMISSION.equals(intent.getAction())) {
            synchronized (this) {
                UsbDevice device = intent.getParcelableExtra("device");
                if (!intent.getBooleanExtra("permission", false)) {
                    onBackMsg(readerCallback, "获取权限失败");
                } else if (device != null) {
                    UsbDeviceConnection connection = mUsbManager.openDevice(device);
                    if (connection != null) {
                        int fileDescriptor = connection.getFileDescriptor();
                        Log.d(TAG, "fileDescriptor:" + fileDescriptor);
                        onBackMsg(readerCallback, "成功获取权限");

                        if (mt3yApi.mt8deviceopenfd(fileDescriptor) > 0) {
                            onBackMsg(readerCallback, "成功打开设备");
                            mt3yApi.mt8devicebeep(258, 1);
                        } else {
                            onBackMsg(readerCallback, "打开设备失败");
                        }
                    }
                }
            }
        }
    }

    private void onBackMsg(IReaderCallback readerCallback, String msg) {
        mReaderBean.setMessage(msg);
        if (readerCallback != null) {
            readerCallback.onMsg(mReaderBean);
        }
    }
}
